package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
//import com.heima.model.common.constants.message.PublishArticleConstants;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
//import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author mrchen
 * @date 2022/4/28 10:50
 */
@Slf4j
@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private GreenScan greenScan;
    @Autowired
    WmNewsService wmNewsService;
    @Value("${file.oss.web-site}")
    private String webSite;
    @Override
    public void autoScanWmNews(Integer id) {
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "id为空，审核失败");
        }
        WmNews wmNews = wmNewsService.getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "对应文章不存在");
        }
        if (!WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(wmNews.getStatus())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章不是审核状态");
        }
        Map<String, Object> contentAndImages = handleTextAndImages(wmNews);
        String content = (String) contentAndImages.get("content");
        List<String> images = (List<String>)contentAndImages.get("images");

        boolean scanSensitive = handleSensitive(content,wmNews);
        if (!scanSensitive){
            log.info("文章中有敏感词");
        return;
        }
        boolean scanText = handleTextScan(content,wmNews);
        if(!scanText){
            // 返回false代表审核不成功   结束处理
            log.info("文章审核未通过，原因: 内容中包含违规词汇");
            return;
        }
        if (images!=null){
            boolean scanImages = handleImageScan((List<String>)contentAndImages.get("images"),wmNews);
            if(!scanImages){
                // 返回false代表审核不成功   结束处理
                log.info("文章审核未通过，原因: 图片中包含违规信息");
                return;
            }
            // 8. 将文章状态改为 8 自动审核通过
        }
            updateWmNews(WmNews.Status.SUCCESS.getCode(), "审核通过",wmNews);
        //5. 通知定时发布文章
        // 发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        System.out.println("发送消息");

    }
@Autowired
    RabbitTemplate rabbitTemplate;
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag = false;
        try {
            ScanResult scanResult = greenScan.imageUrlScan(images);
            switch (scanResult.getSuggestion()){
                case "block":
                    // 失败
                    updateWmNews(WmNews.Status.FAIL.getCode(), "文章图片中违规信息: "+scanResult.getLabel() ,wmNews);
                    break;
                case "review":
                    // 人工
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "文章图片中有不确定因素，需要进一步人工审核" ,wmNews);
                    break;
                case "pass":
                    // 成功
                    flag = true;
                    break;
                default:
                    // 人工
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "阿里云调用状态异常，需要进一步人工审核:" ,wmNews);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 人工审核
            updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "阿里云调用失败，需要进一步人工审核:" ,wmNews);
        }
        return flag;
    }

    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag=false;
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            String suggestion = scanResult.getSuggestion();
            switch (suggestion) {
                case "block":
                    // 失败
                    updateWmNews(WmNews.Status.FAIL.getCode(), "文章内容中包含违规词汇: " + scanResult.getLabel(), wmNews);
                    break;
                case "review":
                    // 人工
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "文章内容中有不确定因素，需要进一步人工审核:", wmNews);
                    break;
                case "pass":
                    // 成功
                    flag = true;
                    break;
                default:
                    // 人工
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "阿里云调用状态异常，需要进一步人工审核:", wmNews);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(),"阿里云调用失败，需要进一步人工审核:" ,wmNews);
        }
        return flag;
    }

    @Autowired
AdminFeign adminFeign;
    private boolean handleSensitive(String content, WmNews wmNews) {
        ResponseResult<List<String>> sensitives = adminFeign.sensitives();
        if (!sensitives.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);

        }
        List<String> sensitivesData = sensitives.getData();
        SensitiveWordUtil.initMap(sensitivesData);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (!CollectionUtils.isEmpty(map)){
            wmNews.setStatus((short)2);
            wmNews.setReason("内容包含敏感词"+map);
            wmNewsService.updateById(wmNews);
            return false;
        }
        return true;
    }

    private void updateWmNews(Short status,String reason,WmNews wmNews){
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);

    }
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        List<Map> maps = JSON.parseArray(wmNews.getContent(), Map.class);
        String content = maps.stream()
                .filter(m -> m.get("type").equals("text"))
                .map(m -> String.valueOf(m.get("value")))
                .collect(Collectors.joining("_hmtt_"));
        content = content + "_hmtt_" + wmNews.getTitle();

        List<String> images = maps.stream()
                .filter(m -> "images".equals(m.get("type")))
                .map(m -> String.valueOf(m.get("value")))
                .collect(Collectors.toList());
        if (StringUtils.isNotBlank(wmNews.getImages())){
            List<String> coverImages = Arrays.stream(wmNews.getImages().split(","))
                    .map(url -> webSite + url)
                    .collect(Collectors.toList());
            images.addAll(coverImages);
        }
        images = images.stream().distinct().collect(Collectors.toList());
        Map result= new HashMap<>();
        result.put("content",content);
        result.put("images",images);
        return result;
    }
}